----一些公共方法
----#include "..\..\language\LangCode.txt" once
--#include "data\functions\Common\CommonScene.lua" once				--场景相关的通用方法
--#include "data\functions\Common\CommonBag.lua" once				--背包相关的通用方法
--#include "data\functions\Common\CommonActivity.lua" once			--活动相关的通用方法
--#include "data\functions\Common\CommonOperation.lua" once			--操作相关的通用方法
--#include "data\functions\Common\CommonTeleport.lua" once			--传送相关的通用方法
--#include "data\functions\Common\CommonAward.lua" once			    --奖励相关的通用方法
--#include "data\functions\Common\CommonAnswer.lua" once			--答题相关的通用方法
--#include "data\functions\Common\CommonRank.lua" once			    --排行榜相关的通用方法
--#include "data\functions\Common\CommonPanel.lua" once			    --面板相关的通用方法
--#include "data\functions\Common\CommomQuest.lua" once			    --任务相关的通用方法

--activetime是{{h1,m1},{h2,m2}}形式(不能跨天)
function CheckTimeValid(time)
	local nHour,nMin,nSec = System.getTime(0,0,0,0)    --当前时间
	local timeBegin = time[1]
	local timeEnd 	= time[2]
	--print("CheckTimeValid, nHour="..nHour..", nMin="..nMin)
	--print("CheckTimeValid, h1="..timeBegin[1]..", m1="..timeBegin[2]..", h2="..timeEnd[1]..", m2="..timeEnd[2])
	if nHour < timeBegin[1] or nHour > timeEnd[1] then		--小开始小时、大于结束小时
		return false
	elseif timeBegin[1] == timeEnd[1]  then    		--起止小时是同一个小时
		if nMin < timeBegin[2] or nMin > timeEnd[2] then	--不在分钟范围之内
			return false
		else
			return true
		end
	elseif timeBegin[1] < timeEnd[1] then		--开始小时小于结束小时
		if nHour == timeBegin[1] and nMin < timeBegin[2] then
			return false
		elseif nHour == timeEnd[1] and nMin > timeEnd[2] then
			return false
		else
			return true
		end
	end
	return false
end

function CheckTimesValid( times )
	for i,time in ipairs(times) do
		if CheckTimeValid(time) then
			return true
		end
	end
	return false
end

--[[某场景内范围刷怪，不足补足，多了不刷
	{ 
		monsterId=15, sceneId=1, num=1, range={100,120,200,420}, livetime=86400,
	},
]]
function freshSceneMonsterInRange(freshMonCfg, fubenHandle)
	--print("freshSceneMonsterInRange, sceneId="..freshMonCfg.sceneId..", monsterId="..freshMonCfg.monsterId)
	fubenHandle = fubenHandle or 0
	if not System.hasScene( freshMonCfg.sceneId, fubenHandle ) then
		print("warning, scene["..freshMonCfg.sceneId.."] is not exist in config to mob monsters")
		return
	end

	local hScene = Fuben.getSceneHandleById(freshMonCfg.sceneId, fubenHandle or 0)
	if hScene then
		local num = freshMonCfg.num - Fuben.getMyMonsterCount(hScene, freshMonCfg.monsterId)
		if num > 0 then
			return Fuben.createMonstersInRange(hScene, freshMonCfg.monsterId, 
				freshMonCfg.range[1], freshMonCfg.range[2], freshMonCfg.range[3], freshMonCfg.range[4], 
				num, freshMonCfg.livetime)
		end
	end
	return 0
end

--[[某场景、副本内范围刷怪，必定刷出
]]
function freshSceneMonsterInRangeForce(freshMonCfg, fubenHandle)
	fubenHandle = fubenHandle or 0
	if not System.hasScene( freshMonCfg.sceneId, fubenHandle ) then
		print("warning, scene["..freshMonCfg.sceneId.."] is not exist in config to mob monsters")
		return
	end

	--print("freshSceneMonsterInRangeForce, sceneId="..freshMonCfg.sceneId..", monsterId="..freshMonCfg.monsterId)
	local hScene = Fuben.getSceneHandleById(freshMonCfg.sceneId, fubenHandle or 0)
	if hScene then
		local num = freshMonCfg.num
		if num > 0 then
			return Fuben.createMonstersInRange(hScene, freshMonCfg.monsterId, 
				freshMonCfg.range[1], freshMonCfg.range[2], freshMonCfg.range[3], freshMonCfg.range[4], 
				num, freshMonCfg.livetime)
		end
	end
	return 0
end

--[[场景内定点刷怪，不足补足，多了不刷
	{ 
		monsterId=15, sceneId=1, num=1, pos={122,171}, livetime=86400,
	},
]]
function freshSceneMonsterInPos(freshMonCfg, fubenHandle)
	fubenHandle = fubenHandle or 0
	if not System.hasScene( freshMonCfg.sceneId, fubenHandle ) then
		print("warning, scene["..freshMonCfg.sceneId.."] is not exist in config to mob monsters")
		return
	end

	--print("freshSceneMonsterInPos, sceneId="..freshMonCfg.sceneId..", fubenHandle="..fubenHandle..", monsterId="..freshMonCfg.monsterId)
	local hScene = Fuben.getSceneHandleById(freshMonCfg.sceneId, fubenHandle or 0)
	if hScene then
		local num = freshMonCfg.num - Fuben.getMyMonsterCount(hScene, freshMonCfg.monsterId)
		if num > 0 then
			--return Fuben.createMonstersInRange(hScene, freshMonCfg.monsterId, 
			--	freshMonCfg.pos[1], freshMonCfg.pos[2], freshMonCfg.pos[1], freshMonCfg.pos[2], 
			--	num, freshMonCfg.livetime)

			Fuben.createMonsters( hScene, freshMonCfg.monsterId, freshMonCfg.pos[1], freshMonCfg.pos[1],
				freshMonCfg.pos[2], num, freshMonCfg.livetime )
		end
	end
	return
end

--[[某场景内定点刷怪，必定刷出
]]
function freshSceneMonsterInPosForce(freshMonCfg, fubenHandle)
	--print("freshSceneMonsterInPosForce, sceneId="..freshMonCfg.sceneId)
	fubenHandle = fubenHandle or 0
	if not System.hasScene( freshMonCfg.sceneId, fubenHandle ) then
		print("warning, scene["..freshMonCfg.sceneId.."] is not exist in config to mob monsters")
		return
	end

	local hScene = Fuben.getSceneHandleById(freshMonCfg.sceneId, fubenHandle or 0)
	if hScene then
		local num = freshMonCfg.num
		if num > 0 then
			Fuben.createMonsters( hScene, freshMonCfg.monsterId, freshMonCfg.pos[1], freshMonCfg.pos[1],
				freshMonCfg.pos[2], num, freshMonCfg.livetime )
		end
	end
	return
end

--[[
定点刷出一个怪，必定刷出
]]
function freshSceneOneMonsterInPos(freshMonCfg, fubenHandle)
	fubenHandle = fubenHandle or 0
	if not System.hasScene( freshMonCfg.sceneId, fubenHandle ) then
		print("warning, scene["..freshMonCfg.sceneId.."] is not exist in config to mob monsters")
		return nil
	end

	fubenHandle = fubenHandle or 0
	--print("freshSceneMonsterInPos, sceneId="..freshMonCfg.sceneId..", fubenHandle="..fubenHandle)
	local hScene = Fuben.getSceneHandleById(freshMonCfg.sceneId, fubenHandle or 0)
	if hScene then
		return Fuben.createMonster( hScene, freshMonCfg.monsterId, freshMonCfg.pos[1], freshMonCfg.pos[2], freshMonCfg.livetime )
	end
	return nil
end


--获取某个场景中的怪物数量
function GetSceneMonsterNum( sceneId, fbHandle, monsterId )
	local hScene = Fuben.getSceneHandleById(sceneId, fbHandle or 0 )
	if hScene then
		return Fuben.getMyMonsterCount(hScene, monsterId)
	end
	return 0
end

--[[ 清除怪物
freshMonConfig =
{ 
	monsterId=15, sceneId=1, num=1, pos={122,171}, livetime=86400,
},
]]--
function clearScenceMonster( freshMonConfig, fbHandle )
	--print(" clearScenceMonster monsterId="..freshMonConfig.monsterId)
	local hScene = Fuben.getSceneHandleById(freshMonConfig.sceneId, fbHandle or 0)
	if hScene then
		Fuben.clearMonster(hScene,  freshMonConfig.monsterId)
	end
end

--[[某副本内刷怪
	不支持怪物等级成长
	{ monsterId=15, sceneId=1, num=1, pos={122,171,122,171}, livetime=86400 },
]]
function freshFuBenMonsterInRange( hFuben, freshMonCfg )
	local hScene = Fuben.getSceneHandleById(freshMonCfg.sceneId, hFuben)
	return Fuben.createMonstersInRange(hScene, freshMonCfg.monsterId, 
				freshMonCfg.pos[1], freshMonCfg.pos[2], freshMonCfg.pos[3], freshMonCfg.pos[4], 
				freshMonCfg.num, freshMonCfg.livetime)
end

--[[某副本内刷怪
	支持怪物等级成长，
	注意，用过此方法创建出来的怪等级是nOriginalLevel+nBornLevel （配置等级+传入等级）
	{ monsterId=15, sceneId=1, num=1, pos={122,171,122,171}, livetime=86400 },
]]
function freshFuBenMonsterInRangeEx( hFuben, freshMonCfg )
	local hScene = Fuben.getSceneHandleById(freshMonCfg.sceneId, hFuben)
	return Fuben.createMonstersInRange(hScene, freshMonCfg.monsterId, 
				freshMonCfg.pos[1], freshMonCfg.pos[2], freshMonCfg.pos[3], freshMonCfg.pos[4], 
				freshMonCfg.num, freshMonCfg.livetime, freshMonCfg.level or 0)
end


function GetElemByRange( elems, value )
	for i,elem in ipairs(elems) do
		if elem.range[1] <= value and value <= elem.range[2] then
			return elem 
		end
	end
	return nil
end

--支持大于21亿的exp
function AddExpToActor(sysarg, exp, logId )
	--print("AddExpToActor, exp="..exp)
	Actor.addExp(sysarg, exp, logId, 0)
	-- local expLimit = 2100000000
	-- if exp <= expLimit then
		
	-- else
	-- 	local expRate = math.floor(exp/expLimit)   --向下取整
	-- 	local expMore = math.mod(exp,expLimit)

	-- 	for i=1, expRate do
	-- 		Actor.addExp(sysarg, expLimit, logId, 0)
	-- 	end
	-- 	if expMore > 0 then
	-- 		Actor.addExp(sysarg, expMore, logId, 0)
	-- 	end
	-- end
end


function GetEntityPos( entityPtr )
	local posX = Actor.getIntProperty(entityPtr, PROP_ENTITY_POSX)
	local posY = Actor.getIntProperty(entityPtr, PROP_ENTITY_POSY)
	return posX, posY
end





---------------------------------------------------------------------------------------------------
--[[
levelNeedFee = 
	{
		--{cond=等级段，resetItem=重置需要的道具, resetFee=重置需要的费用, finishFee=立即完成的费用
		{ cond={50,59}, resetItem = {510, 1}, resetFee={3, 100}, finishFee={3,50}, },
		{ cond={60,69}, resetItem = {510, 2}, resetFee={3, 200}, finishFee={3,150}, },
		{ cond={70,79}, resetItem = {510, 3}, resetFee={3, 300}, finishFee={3,250}, },
		{ cond={80,89}, resetItem = {510, 4}, resetFee={3, 400}, finishFee={3,350}, },
		{ cond={90,99}, resetItem = {510, 5}, resetFee={3, 500}, finishFee={3,550}, },
	},
]]
function GetElemByCond( elems, condValue )
	for i, elem in ipairs(elems) do
		if elem.cond[1] <= condValue and condValue <= elem.cond[2] then
			return elem
		end
	end
	return nil
end

--根据两个条件匹配  这里额外处理了不能判断0 
function GetElemMatch2Cond( elems, condValue1, condValue2 )
	--print("GetElemMatch2Cond, condValue1="..condValue1..", condValue2="..condValue2)
	if condValue2 and condValue2 > 0 then
		for i, elem in ipairs(elems) do
			if elem.cond[1] == condValue1 and elem.cond[2] == condValue2 then
				--print("GetElemMatch2Cond, xxx1")
				return elem
			end
		end
	else
		for i, elem in ipairs(elems) do
			if elem.cond[1] == condValue1 then
				return elem
			end
		end
	end
	return nil
end

--根据两个条件匹配  满足的都算在内， 这里额外处理了不能判断0 
function GetAllMatchElemsByCond( elems, condValue1, condValue2 )
	local data = {}
	if condValue2 and condValue2 > 0 then
		for i, elem in ipairs(elems) do
			if elem.cond[1] <= condValue1 and elem.cond[2] <= condValue2 then
				table.insert(data, elem)
			end
		end
	else
		for i, elem in ipairs(elems) do
			if elem.cond[1] == condValue1 then
				table.insert(data, elem) 
			end
		end
	end
	return data
end

function GetElemByOpenServerDay( elems )
	local openDay = System.getDaysSinceOpenServer()
	--print("GetElemByOpenServerDay, openDay="..openDay)
	for i, elem in ipairs( elems or {} ) do
		--print("GetElemByOpenServerDay, openServerDay[1]="..elem.openServerDay[1]..", elem.openServerDay[2]="..elem.openServerDay[2])
		if elem.openServerDay[1] <= openDay and openDay <= elem.openServerDay[2] then
			return elem
		end
	end
	return nil
end

--[[
判断是否命中
elem.rate:万分比概率
]]
function CheckCommonRandomRateHit( elems, condValue )
	local elem = GetElemByCond( elems, condValue )
	if elem and elem.rate then
		local randNum = System.getRandomNumber( 10000 ) + 1
		--print( "CheckCommonRandomRateHit, randNum="..randNum..", rate="..elem.rate )
		if elem.rate >= randNum then
			return true
		end
	end
	return false
end

--[[判断开服天数]]
function CheckOpenServerDay( cfg )
	local openDays = System.getDaysSinceOpenServer()
	--print( "CheckOpenServerDay, openDays="..openDays..", openServerDay="..cfg.openServerDay )
	if cfg.openServerDay and cfg.openServerDay > 0 and openDays < cfg.openServerDay then
		return false
	end
	return true
end


--[[
判断当前是开服前N天或合服前N天
OpenOrCombServerDay = { N1, N2 },  
	N1为0，只要求合服前N天
	N2为0，只要求开服前N天
]]
function CheckOpenOrCombServerDayBegore( OpenOrCombServerDay )
	local openDays = System.getDaysSinceOpenServer() 			--openDays>0 才算开服
	local combDays = System.getDaysSinceCombineServer()			--combDays>0 才算合服
	print("CheckOpenOrCombServerDayBegore, openDays="..openDays..", combDays="..combDays)
	if 	OpenOrCombServerDay[1] > 0 and OpenOrCombServerDay[2] > 0 then 			    --要求开服前N1天或者合服前N2天
		if openDays > 0 and openDays <= OpenOrCombServerDay[1] or combDays > 0 and combDays <= OpenOrCombServerDay[2] then
			return true
		end
	elseif OpenOrCombServerDay[1] <= 0 and OpenOrCombServerDay[2] > 0 then 			--只要求合服前N2天
		if combDays > 0 and combDays <= OpenOrCombServerDay[2] then
			return true
		end
	elseif OpenOrCombServerDay[2] <= 0 and OpenOrCombServerDay[1] > 0 then 			--只要求开服前N1天
		if openDays > 0 and openDays <= OpenOrCombServerDay[1] then
			return true
		end
	elseif OpenOrCombServerDay[1] <= 0 and OpenOrCombServerDay[2] <= 0 then 		--都不做要求
		return true
	end
	return false
end

--[[
开服天数在范围之内
]]
function IsOpenServerDayInRange( openDayRange )
	local openDays = System.getDaysSinceOpenServer()
	return openDayRange[1] <= openDays and openDays <= openDayRange[2]
end

--[[判断合服天数]]
function CheckCombineServerDay( combDaysBegin, combDaysEnd )
	if not combDaysBegin or not combDaysEnd then
		return false
	end
	local combDays = System.getDaysSinceCombineServer()
	if combDaysBegin <= combDays  and combDays <= combDaysEnd then
		return true
	end
	return false
end


function CheckVip( sysarg, vipGrade )
	return Actor.getVipGrade( sysarg ) >= vipGrade
end

--[[
通知玩家获得某个活动的实际奖励(已经不使用)
注意：某些奖励可能是动态计算的
activeId：见enum tagCommonActiveIDDef定义
result:0-失败，1-胜利
]]
function NoticeActiveAward( sysarg, activeId, result, awards )
	--print("NoticeActiveAward, activeId="..activeId..", result="..result)
	local netPack = DataPack.allocPacket(sysarg, 139, enScriptMiscSystemcNoticeActivityAward)
	if netPack then
	    DataPack.writeChar(netPack, activeId)
	    DataPack.writeChar(netPack, result)
		DataPack.writeChar(netPack, #awards) 
		for i,award in ipairs(awards) do
			DataPack.writeChar(netPack, award.type)
			DataPack.writeInt(netPack, award.id)
			DataPack.writeUInt(netPack, award.count)
			--print("NoticeActiveAward, type="..award.type..", id="..award.id..", count="..award.count)
		end
	    DataPack.flush(netPack)
	end
end

function BroadMsgInScence( sceneId, msg, flag)
	local playerList = LuaHelp.getSceneActorListById( sceneId ) or {}
	for i,player in ipairs(playerList) do
		Actor.sendTipmsg(player, msg, flag)
	end
end

--[[
把fromTable加入到totable中
]]
function Merge2Table( totable, fromTable )
	for i, elem in ipairs( fromTable or {} ) do
		table.insert( totable, elem )
	end
end


function IsElemInList( elemList, value )
	for i, elem in ipairs( elemList or {} ) do
		if value == elem then
			return true
		end
	end
	return false
end
--table to string
BaseFuc_serialize = function( obj )
	local lua = ""
	local t = type( obj )
	if t == "number" then
		lua = lua .. obj
	elseif t == "boolean" then
		lua = lua .. tostring( obj )
	elseif t == "string" then
		lua = lua .. string.format( "%q", obj )
	elseif t == "table" then
		lua = lua .. "{"
		for k, v in pairs( obj ) do
			lua = lua .. "[" .. BaseFuc_serialize( k ) .. "]=" .. BaseFuc_serialize( v ) .. ","
		end
		local metatable = getmetatable( obj )
			if metatable ~= nil and type( metatable.__index ) == "table" then
			for k, v in pairs( metatable.__index ) do
				lua = lua .. "[" .. BaseFuc_serialize( k ) .. "]=" .. BaseFuc_serialize( v ) .. ","
			end
		end
		lua = lua .. "}"
	elseif t == "nil" then
		return nil
	else
		error( "can not BaseFuc_serialize a " .. t .. " type." )
	end
	return lua
end

--string to table
BaseFuc_unserialize = function( lua )
	local t = type( lua )
	if t == "nil" or lua == "" then
		return nil
	elseif t == "number" or t == "string" or t == "boolean" then
		lua = tostring( lua )
	else
		error( "can not unserialize a " .. t .. " type." )
	end
	lua = "return " .. lua
	local func = loadstring( lua )
	if func == nil then
		return nil
	end
	return func()
end

--[[
--]]
function GetAwardsByRate( awards, rate )
	local newAwards = {}
	for i, award in ipairs(awards) do
		local newAward={}
		newAward.type 				= award.type
		newAward.id 				= award.id
		newAward.count 				= award.count*rate
		newAward.quality 			= award.quality
		newAward.strong				= award.strong
		newAward.bind				= award.bind
		newAward.qualityDataIndex	= award.qualityDataIndex
		table.insert(newAwards, newAward)
	end
	return newAwards
end


--[[合并奖励]]
function MergeAward(awards1,awards2)
	local awards = {}
	if not awards1 or awards1 == {} then
		return awards2
	end
	if not awards2 or awards2 == {} then
		return awards1
	end
	local awards1 = table.deepcopy(awards1)
	for i, award1 in ipairs(awards1) do
		for j, award2 in ipairs(awards2) do
			if not award2.isUse and award1.type == award2.type and award1.id == award2.id and award1.bind == award2.bind then
				award1.count = award1.count + award2.count
				award2.isUse = 1
			end
		end
		table.insert(awards, award1)
	end
	for i, award2 in ipairs(awards2) do
		if not award2.isUse then
			table.insert(awards, award2)
		end
	end
	return awards
end
function MergeAward2(awards1)
	local awards1 = table.deepcopy(awards1)
	local awards = {}
	for i,v in ipairs(awards1) do
		local isUse = false
		for i2,v2 in ipairs(awards) do
			if v2.id == v.id and v2.type == v.type then
				v2.count = v2.count + v.count
				isUse = true
				break
			end
		end
		if not isUse then
			table.insert(awards, v)
		end
	end
	return awards
end
--[[
合并副本奖励，即相同type的奖励累加（仅数值类型）
]]
function MergeFubenAwards( fubenPtr, awards )
	for i, award in ipairs( awards ) do
		--print("MergeFubenAwards, type="..award.type..", count="..award.count)
		Fuben.mergeAwards( fubenPtr, award.type, award.count )
	end
end

--[[
获取合并后的副本奖励
]]
function GetFubenAwardsMerged( fubenPtr )
	local awardsMerged = {}
	for awardType=qatExp, qatMax do
		local awardCount = Fuben.getAwarsMerged( fubenPtr, awardType )
		if awardCount > 0 then
			local awardMerged 	= {}
			awardMerged.type  	= awardType
			awardMerged.id 	  	= 0
			awardMerged.count 	= awardCount
			awardMerged.quality = 0
			awardMerged.bind  	= 1
			table.insert( awardsMerged, awardMerged )
		end
	end
	return awardsMerged
end

--[[暂不使用
award：是{}类型
toAwards:是 { {},{} }类型
返回值：toAwards
toAwards会改变，在调用之前，可能需要对toAwards先进行深拷贝，以免污染原始配置

function AddAwardToAwards( award, toAwards )
	if not award or award == {} then
		return toAwards
	end

	if not toAwards or #toAwards == 0 then
		return { award }
	end

	print("AddAwardToAwards 1, type="..award.type..", id="..award.id..", count="..award.count)
	for i, toAward in ipairs( toAwards ) do
		if award.type == toAward.type and award.id == toAward.id and award.bind == toAward.bind then
			print("AddAwardToAwards 2, type="..toAward.type..", id="..toAward.id..", count="..toAward.count)
			toAward.count = toAward.count + award.count
			return toAwards
		end
	end
	table.insert( toAwards, award )
	return toAwards
end
]]


function AddAwardsToAwards( fromAwards, toAwards )
	if not fromAwards or #fromAwards == 0 then
		return toAwards
	end

	if not toAwards or #toAwards == 0 then
		return fromAwards
	end

	local newAwards = {}
	for j, fromAward in ipairs( fromAwards ) do
		for i, toAward in ipairs( toAwards ) do
			local needInsert = true
			if toAward.type == fromAward.type and toAward.id == fromAward.id and toAward.bind == fromAward.bind then
				print("AddAwardsToAwards 1, type="..toAward.type..", id="..toAward.id..", count="..toAward.count..", addCount="..fromAward.count)
				toAward.count = toAward.count + fromAward.count
				needInsert = false
				break
			end

			if needInsert then
				local newAward = DeepCopyFromObject( fromAward ) 			--必须要深拷贝
				print("AddAwardsToAwards 2, type="..newAward.type..", id="..newAward.id..", count="..newAward.count)
				table.insert( newAwards, newAward )
			end
		end
	end

	for i, award in ipairs( newAwards ) do
		table.insert( toAwards, award )
	end
	return toAwards
end


--判断两个物品的GUID是否一样, 返回true不一样, false有一样的
function CheckItemGuidSame( guidList, guid)
	for i = 1, table.getn( guidList) do
		if Item.IsGuidSame( guidList[i], guid ) then 		--已经存在了
			return false
		end
	end
	return true
end

--[[
取消，空方法
]]
function FunctionCancel( sysarg )

end


--[[合并奖励简洁版]]
function EasyMergeAward(awards1,awards2)
	if not awards1 or awards1 == {} then
		return awards2
	end
	if not awards2 or awards2 == {} then
		return awards1
	end
	for i, award2 in ipairs(awards2) do
		table.insert(awards1, award2)
	end
	return awards1
end

------------------------------随机抽取----begin---------------------------------------
--随机抽取
--返回 下标,元素
function GetItemIdxRand(items)
	local weightAll = GetWeightAll(items)
	local num = math.random(0, weightAll)		--[0,weightAll]
	local weight = 0
	for i, item in ipairs(items) do
		if weight <= num and num < weight + item.weight then
			return i, item
		end
		weight = weight + item.weight
	end
	return #items, items[#items]
end


--[[随机抽取
返回 下标,元素
]]
function GetItemIdxRandNoWeight(items)
	local weightAll = #items
	local idx = math.random(1, weightAll)		--[0,weightAll]
	return idx, items[idx]
end


function GetWeightAll(items)
	local weightAll = 0
	for i,item in ipairs(items) do
		weightAll = weightAll + item.weight
	end
	return weightAll
end


function GetItemIdxsRand(items, needNum) 
	local weightList = {}
	local weightAll = 0
	local answer = {}
	local answerIndex = {}

	if needNum <= 0 then
		return answer
	end

	if #items <= needNum then
		return items
	end

	for ii = 1, #items do
		weightAll = weightAll + items[ii].weight
		weightList[ii] = items[ii].weight
	end

	for idx = 1, needNum do
		local state = 0
		local weight = 0
		local num = System.getRandomNumber(weightAll)
		for i, value in pairs(weightList) do
			if value then
				if weight <= num and num < weight + value then
					answer[idx] = items[i]
					answerIndex[idx] = i
					weightList[i] = nil
					weightAll = weightAll - value
					state = 1
					break
				end
				weight = weight + value
			end
		end
		if state == 0 then
			for y = #items,1,-1 do
				if weightList[y] then
					answer[idx] = items[y]
					answerIndex[idx] = y
					weightAll = weightAll - weightList[y]
					weightList[y] = nil
					break
				end
			end
		end
	end
	return answer, answerIndex
end


--[[获取元素的分布,
isSame：是否允许重复
elems = {{pos = 1, weight = 0},
		 {pos = 2, weight = 10},
		 {pos = 3, weight = 30},
	}
返回：元素列表
]]
function DistributeElem(elems, num, isSame)
	if num > #elems then
		return
	end

	local tmpElems = {}
	for i, elem in ipairs(elems) do
		table.insert(tmpElems, elem)
	end

	local elemList = {}
	for i=1, num do
		local idx, elem = GetItemIdxRand(tmpElems)
		if not isSame then
			table.remove(tmpElems, idx)
		end
		table.insert(elemList, elem)
		--print("DistributeElem, idx="..idx..", pos="..elem.pos)
	end
	return elemList   --已经包括elem在lib中的index
end

--[[获取元素的分布
可以根据玩家的职业、性别过滤
isSame：是否允许重复
elems = {{pos = 1, weight = 0},
		 {pos = 2, weight = 10},
		 {pos = 3, weight = 30},
	}
返回：元素列表
]]
function DistributeElemByActor(sysarg, elems, num, isSame)
	--print("DistributeElemByActor, num="..num)
	if num > #elems then
		return
	end

	--print("DistributeElemByActor, xxx2")
	local filterElems = FilterCommonAwards( sysarg, elems )   --首先进行过滤
	local tmpElems = {}
	for i, elem in ipairs(filterElems) do
		table.insert(tmpElems, elem)
	end

	local elemList = {}
	for i=1, num do
		local idx, elem = GetItemIdxRand(tmpElems)
		if not isSame then
			table.remove(tmpElems, idx)
		end
		table.insert(elemList, elem)
		--print("DistributeElemByActor, idx="..idx..", itemIdx="..elem.itemIdx)
	end
	return elemList   --已经包括elem在lib中的index
end


---------------------------------------------------------------------------
--[[
从库中随机抽取元素
返回：原始下标及其对应的元素
]]

--[[

]]
function GetWeightAllExt(items)
	local weightAll = 0
	for i,item in ipairs(items) do
		if not item.hasChose then				--尚未被抽取
			weightAll = weightAll + item.weight
		end
	end
	return weightAll
end

--随机抽取
--返回 下标
function GetItemIdxRandExt(items)
	local weightAll = GetWeightAllExt( items )
	local num = math.random(0, weightAll)		--[0,weightAll]
	local weight = 0
	for i, item in ipairs(items) do
		if not item.hasChose then				--尚未被抽取
			if weight <= num and num < weight + item.weight then
				return i, item
			end
			weight = weight + item.weight
		end
	end
	return #items, items[#items]
end

--[[
（暂不要使用这个方法）
从一群元素中，按权重随机抽若干元素，返回table的下标是在原始元素中的下标
即 newTable[在原始集合中的下标]=被抽取元素
要用key-value方式访问
注意：elems是原始元素集合的深度拷贝的副本，而不要是原始元素集合本身，因为会把已被抽取的值设置为‘被抽取’
从而影响下一次调用
]]
function DistributeElemKey(elems, num, isSame)
	if num > #elems then
		return
	end

	local elemList = {}
	for i=1, num do
		local idx, elem = GetItemIdxRandExt( elems ) 		--随机抽取一个元素，返回：下标+元素
		if not isSame then
			elems[idx].hasChose = true 		                --该元素已经被抽取了
		end
		elemList[idx] = elem
		--print("DistributeElemKey, idx="..idx)
	end
	return elemList   --已经包括elem在lib中的index
end

------------------------------随机抽取----end----------------------------------------
function CheckConsumeMoney( sysarg, moneyType, moneyNum, rate, sendMsg )
	--print("CheckConsumeMoney, moneyType="..moneyType..", moneyNum="..moneyNum)
	local consumes = nil
	if moneyType == mtYuanbao then			    --元宝
		consumes = { { type = qatYuanbao, id = 0, count = moneyNum,} }
	elseif moneyType == mtBindYuanbao then		--绑元
		consumes = { { type = qatBindYb, id = 0, count = moneyNum,} }
	elseif moneyType == mtBindCoin then		    --金币
		consumes = { { type = qatBindMoney, id = 0, count = moneyNum,} }
	end

	if consumes then
		return CheckConsumeCond( sysarg, consumes, rate, sendMsg )
	end
	return false
end

function DoConsumeMoney( sysarg, moneyType, moneyNum, rate, logId, logStr, sendMsg  )
	local consumes = nil
	if moneyType == mtYuanbao then			    --元宝
		consumes = { { type = qatYuanbao, id = 0, count = moneyNum,} }
	elseif moneyType == mtBindYuanbao then		--绑元
		consumes = { { type = qatBindYb, id = 0, count = moneyNum,} }
	elseif moneyType == mtBindCoin then		    --金币
		consumes = { { type = qatBindMoney, id = 0, count = moneyNum,} }
	end

	if consumes then
		return DoConsumeCond( sysarg, consumes, rate, logId, logStr, sendMsg  )
	end
	return false
end

--[[检查是否满足消费条件
rate:倍数
sendMsg:是否瓢字而不是弹窗
注意：quality、strong、bind：不填或者-1，表示都算在内
bind：不填或者-1，表示非绑+绑定+不可交易都算在内
]]
function CheckConsumeCond( sysarg, consumes, rate, sendMsg )
	local consumeRate = rate or 1
	for k,v in pairs( consumes ) do
		local bCheck = Actor.checkConsume(sysarg, v.type, v.id, v.count*consumeRate, v.quality or 0, v.strong or -1, 
			v.bind or -1) 
		if bCheck ~= true then
			if sendMsg then
				local itemName = Item.getAwardDesc( v.type, v.id )
				Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.COM0044, itemName ),ttFlyTip)
			else
				Actor.sendItemLack( sysarg, v.type, v.id, v.count*consumeRate )
			end
			return false
		end
	end

	return true
end

function CheckConsumeCondNoTip( sysarg, consumes, rate )
	local consumeRate = rate or 1
	for k,v in pairs( consumes ) do
		local bCheck = Actor.checkConsume(sysarg, v.type, v.id, v.count*consumeRate, v.quality or 0, v.strong or -1, 
			v.bind or -1) 
		if bCheck ~= true then
			return false
		end
	end

	return true
end
--[[扣除消费，必须先判断CheckConsumeCond
rate:倍数
]]
function DoConsumeCond( sysarg, consumes, rate, logId, logStr, sendMsg  )
	local consumeRate = rate or 1
	for k,v in pairs( consumes ) do
		local removeCount = Actor.removeConsume(sysarg, v.type, v.id, v.count*consumeRate, v.quality or 0, v.strong or -1, 
			v.bind or -1, 0, logId,logStr) 
		if removeCount < v.count*consumeRate then
			if sendMsg then
				local itemName = Item.getAwardDesc( v.type, v.id )
				Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.COM0044, itemName ),ttFlyTip)
			else
				Actor.sendItemLack( sysarg, v.type, v.id, v.count*consumeRate )
			end
			return false
		end
	end
	return true
end



--[[
检查是否满足消费条件
支持可替代
consume =  { type = 0, id = 1101, count = 1 },       --消耗
unitConsume = { type = 5, id = 0, count = 100 },       --单位替代消耗
	unitConsume.count：=0-不替代，>0-替代
如果替代，当数量不足时，则先扣除拥有的，再按缺少数量扣除替代物
]]
function CheckConsumeCondWithReplace( sysarg, consume, unitConsume )
	if unitConsume.count > 0 then 		--需要替代
		local hasCount = Actor.hasConsumeNum(sysarg, consume.type, consume.id, consume.count, consume.quality or 0, 
			consume.strong or 0, consume.bind or -1)
		local diffCount = consume.count - hasCount 	--缺少的数量
		--print("CheckConsumeCondWithReplace, hasCount="..hasCount..", needCount="..consume.count..", diffCount="..diffCount)
		if diffCount > 0 then			--数量不足
			local replaceCount = unitConsume.count * diffCount
			local consume2 = { type=unitConsume.type, id=unitConsume.id, count=replaceCount, } --替代扣费
			--print("CheckConsumeCondWithReplace, replaceCount="..replaceCount)
			return CheckConsumeCond( sysarg, {consume2}, 1)
		else 	--数量足够
			return true
		end
	else 		--不替代
		return CheckConsumeCond( sysarg, {consume}, 1)
	end
end

--[[扣除消费，必须先判断CheckConsumeCondWithReplace
如果替代，当数量不足时，则先扣除拥有的，再按缺少数量扣除替代物
unitConsume.count：=0-不替代，>0-替代
]]
function DoConsumeCondWithReplace( sysarg, consume, unitConsume, logId, logStr )
	if unitConsume.count > 0 then 		--需要替代
		local hasCount = Actor.hasConsumeNum(sysarg, consume.type, consume.id, consume.count, consume.quality or 0, 
			consume.strong or 0, consume.bind or -1)
		local diffCount = consume.count - hasCount 	--缺少的数量
		--print("DoConsumeCondWithReplace, hasCount="..hasCount..", needCount="..consume.count..", diffCount="..diffCount)
		if diffCount > 0 then			--数量不足
			local replaceCount = unitConsume.count * diffCount
			local consume1 = { type=consume.type, id=consume.id, count=hasCount, }
			local consume2 = { type=unitConsume.type, id=unitConsume.id, count=replaceCount, } --替代扣费
			--print("DoConsumeCondWithReplace, replaceCount="..replaceCount)
			if not DoConsumeCond( sysarg, {consume1}, 1, logId, logStr ) then
				return false 
			end

			if not DoConsumeCond( sysarg, {consume2}, 1, logId, logStr ) then
				return false 
			end
			return true
		else 	--数量足够
			return DoConsumeCond( sysarg, {consume}, 1, logId, logStr  )
		end
	else 		--不替代
		return DoConsumeCond( sysarg, {consume}, 1, logId, logStr  )
	end
end
	
--[[删除某玩家身上某种道具]]
function RemoveActorItemInBag( sysarg, delItemId, logId, logStr )
	local itemCount = Actor.getItemCount( sysarg, delItemId )
	--print("RemoveActorItemInBag, delItemId="..delItemId..", itemCount="..itemCount)
	if itemCount > 0 then
		Actor.removeItem(sysarg, delItemId, itemCount, -1,-1, -1, logStr,logId)
	end
end

--[[
获取table中元素的数量，key可能是离散分布的
]]
function GetElemsNum( elems )
	local num = 0
	for k,v in pairs( elems or {} ) do
		num = num +1
	end
	return num
end


--[[
返回：奖励物品Name1 x N1,Name2 x N2...,Name2 x N2格式

function GetCommonAwardsStr( awards )
	local awardsStr = ""
	for i, award in ipairs( awards ) do
		local name = Item.getAwardDesc(award.type, award.id)
		if not name then
			name = Lang.Script.comm019
		end
		awardsStr = awardsStr..name.." x "..tostring(award.count)
		if i < #awards then
			awardsStr = awardsStr..","
		end
	end
	--print("GetCommonAwardsStr. awardsStr ="..awardsStr)
	return awardsStr
end
]]

--[[发送活动数据
falg:
]]
function SendCommSingleValue(sysarg, valueType, value)

end


function OnActorAddExp( sysarg, addExp, way )
	if way == 334 or way == 335 then
		OnDailyAnswerActorAddExp( sysarg, addExp )
	end
end

--[[
深度拷贝
只要是table类型就分解
]]
function DeepCopyFromObject( object )      
    local SearchTable = {}  
    local function Func(object)  
        if type(object) ~= "table" then  
            return object         
        end  
        local NewTable = {}  
        SearchTable[object] = NewTable  
        for k, v in pairs(object) do  
            NewTable[Func(k)] = Func(v)  
        end     
       
        return setmetatable(NewTable, getmetatable(object))      
    end    
  
    return Func(object)  
end

function GetFirstAwardNumByType( awards, awardType )
	for i,award in ipairs( awards ) do
		--print("GetFirstAwardNumByType, awardType="..awardType..", type="..award.type)
		if award.type == awardType then
			return award.count
		end
	end
	return 0
end

--[[
对于某些类型的奖励，需要进行转换
由于邮件系统已经封装，所以在发送之前由各个功能自行转换，而不是由邮件系统转换
]]
function TransAwardsByType( awards, actorLevel )
	--print("TransAwardsByType, actorLevel="..actorLevel)
	local newAwards = {}
	for i, award in ipairs(awards) do
		--print( "TransAwardsByType, type="..award.type..", count="..award.count )
		if award.type == qatAddExp then			--把经验库经验转换成绝对经验
			local newAward  = {}				--必须用新的table，否则会改动原始配置
			local expLibId 	= award.id
			local rate 		= award.count
			local vipAddRate= award.quality or 0

			newAward.count  = System.getExpFromExpLib(actorLevel, expLibId, rate, vipAddRate)
			newAward.type 	= qatExp
			newAward.id 	= 0
			newAward.quality = 0
			newAward.bind = 0 
			table.insert( newAwards, newAward)
		else
			table.insert( newAwards, award)
		end
	end
	return newAwards
end


--[[
打印堆栈信息
]]
function printCallStack()
	open_debug()
  local startLevel = 2 --0表示getinfo本身,1表示调用getinfo的函数(printCallStack),2表示调用printCallStack的函数,可以想象一个getinfo(0级)在顶的栈.
  local maxLevel = 10 --最大递归10层

  for level = startLevel, maxLevel do
    -- 打印堆栈每一层
    local info = debug.getinfo( level, "nSl") 
    if info == nil then break end
    print( string.format("[ line : %-4d]  %-20s :: %s", info.currentline, info.name or "", info.source or "" ) )

    -- 打印该层的参数与局部变量
    local index = 1 --1表示第一个参数或局部变量, 依次类推
    while true do
      local name, value = debug.getlocal( level, index )
      if name == nil then break end

      local valueType = type( value )
      local valueStr
      if valueType == 'string' then
        valueStr = value
      elseif valueType == "number" then
        valueStr = string.format("%.2f", value)
      end
      if valueStr ~= nil then
        print( string.format( "\t%s = %s\n", name, value ) )
      end
      index = index + 1
    end
  end
end

--怪物名字删除最后几位数字
function MonsterNameDeleteNumber(monsterId)
	local monName = System.getMonsterNameById(monsterId) or ""
	if monName ~= "" then
		local len = string.len(monName)
		for idx = len , 2, -1 do
			local pos = string.len(monName)
			local lastNum = tonumber(string.sub(monName, -1))
			if lastNum and lastNum >= 0 and lastNum <= 9 then
				monName = string.sub(monName, 1, -2)
			else
				return monName
			end
		end
	end	
	return monName
end

--获取头顶物品第几个物品id
function GetPropertyHeadItemValue(sysarg, Idx)
	local PropValue1 = Actor.getUIntProperty(sysarg, PROP_ACTOR_HEAD_ITEM1)
	local PropValue2 = Actor.getUIntProperty(sysarg, PROP_ACTOR_HEAD_ITEM2)
	if Idx  == 1 then
		return  System.getInt2Byte(PropValue1, true)
	elseif Idx == 2 then
		return  System.getInt2Byte(PropValue1, false)
	elseif Idx == 3 then
		return  System.getInt2Byte(PropValue2, true)
	elseif Idx == 4 then
		return  System.getInt2Byte(PropValue2, false)
	end
	return 0
end

--设置头顶物品第几个物品id
function SetPropertyHeadItemValue(sysarg, Idx, Value)
	local PropValue1 = Actor.getUIntProperty(sysarg, PROP_ACTOR_HEAD_ITEM1)
	local PropValue2 = Actor.getUIntProperty(sysarg, PROP_ACTOR_HEAD_ITEM2)
	local NewValue
	local PropValue
	if Idx  == 1 then
		NewValue = System.setInt2Byte(PropValue1, true, Value)
		PropValue = PROP_ACTOR_HEAD_ITEM1
	elseif Idx == 2 then
		NewValue = System.setInt2Byte(PropValue1, false, Value)
		PropValue = PROP_ACTOR_HEAD_ITEM1
	elseif Idx == 3 then
		NewValue = System.setInt2Byte(PropValue2, true, Value)
		PropValue = PROP_ACTOR_HEAD_ITEM2
	elseif Idx == 4 then
		NewValue = System.setInt2Byte(PropValue2, false, Value)
		PropValue = PROP_ACTOR_HEAD_ITEM2
	end
	Actor.setUIntProperty(sysarg, PropValue, NewValue)
end


function SeperateNumByMode( num, mode )
	local num1 = math.floor( num/mode )
	local num2 = math.fmod(num,mode)
	return num1, num2
end

--奖励table打印
function PrintAwardsTable(awards)
	print("startAwardsPrint")
	for idx, award in ipairs(awards) do
		print("idx = "..idx)

		local awardType = award.type or 0
		print("type = "..awardType)

		local awardId = award.id or 0
		print("id = "..awardId)

		local awardCount = award.count or 0
		print("count = "..awardCount)

		local awardQuality = award.quality or 0
		print("quality = "..awardQuality)

		local awardStrong = award.strong or 0
		print("strong = "..awardStrong)

		local awardBind = award.bind or -1
		print("bind = "..awardBind)

		local awardQualityDataIndex = award.qualityDataIndex or 0
		print("qualityDataIndex = "..awardQualityDataIndex)
	end
	print("endAwardsPrint")
end

function GetRandPosInRange( range )
	local x1 = range[1][1]
	local y1 = range[1][2]
	local x2 = range[2][1]
	local y2 = range[2][2]

	local  posX = 0
	local  posY = 0
	if x2 >= x1 and y2 >= y1 then
		posX = math.random( x1, x2 )
		posY = math.random( y1, y2 )
	end
	return posX, posY
end

function getRandomNumberExpertList(number, list)
	local has = {}
	local inList = false
	local ranNum = System.getRandomNumber(number - #list) + 1
	local value = 0
	for idx = 1, #list do
		has[list[idx]] = 1
	end
	for idx = 1, number do
		if not has[idx] then
			value = value + 1
			if value == ranNum then
				return idx, inList
			end
		end
	end
	local Value = System.getRandomNumber(number) + 1
	if has[Value] == 1 then
		inList = true
	end
	return Value, inList
end


--保存世界信息 
--act_id定义到GlobalDefine中的RecordTableIndexDefine里面
--data包含4个参数，至少一个参数不为nil
function setRecordGlobalTableData(act_id, data, len)
	--print("act_id ="..act_id)
	--print("len ="..len)
	local sVar = InfoGlobalTable
	if not sVar.recordGlobalData then
		sVar.recordGlobalData = {}
	end
	if not sVar.recordGlobalData[act_id] then
		sVar.recordGlobalData[act_id] = {}
	end
	if not sVar.recordGlobalIndex then
		sVar.recordGlobalIndex = {}
	end
	if not sVar.recordGlobalIndex[act_id] then
		sVar.recordGlobalIndex[act_id] = 1
	end
	if not sVar.recordGlobalCircle then
		sVar.recordGlobalCircle = {}
	end
	if not sVar.recordGlobalCircle[act_id] then
		sVar.recordGlobalCircle[act_id] = 1
	end
	if data.param or data.param1 or data.param2 or data.param3 then
		sVar.recordGlobalData[act_id][sVar.recordGlobalIndex[act_id]] = {}
		sVar.recordGlobalData[act_id][sVar.recordGlobalIndex[act_id]].param = data.param
		sVar.recordGlobalData[act_id][sVar.recordGlobalIndex[act_id]].param1 = data.param1
		sVar.recordGlobalData[act_id][sVar.recordGlobalIndex[act_id]].param2 = data.param2
		sVar.recordGlobalData[act_id][sVar.recordGlobalIndex[act_id]].param3 = data.param3
		sVar.recordGlobalIndex[act_id] = sVar.recordGlobalIndex[act_id] + 1
		if sVar.recordGlobalIndex[act_id] > len then
			sVar.recordGlobalCircle[act_id] = sVar.recordGlobalCircle[act_id] + 1 
			sVar.recordGlobalIndex[act_id] = sVar.recordGlobalIndex[act_id] - len
		end
	end
end

--获取世界信息 act_id定义到GlobalDefine中的RecordTableIndexDefine里面
--data包含4个参数，至少一个参数不为nil
function getRecordGlobalTableData(act_id, circle, index, len)
	--print("circle ="..circle)
	--print("index ="..index)
	--print("len ="..len)
	if not circle or circle < 1 then
		circle = 1 
	end
	if not index or index < 1 then
		index = 1
	end
	local sVar = InfoGlobalTable
	if not sVar.recordGlobalData then
		sVar.recordGlobalData = {}
	end
	if not sVar.recordGlobalData[act_id] then
		sVar.recordGlobalData[act_id] = {}
	end
	if not sVar.recordGlobalIndex then
		sVar.recordGlobalIndex = {}
	end
	if not sVar.recordGlobalIndex[act_id] then
		sVar.recordGlobalIndex[act_id] = 1
	end
	if not sVar.recordGlobalCircle then
		sVar.recordGlobalCircle = {}
	end
	if not sVar.recordGlobalCircle[act_id] then
		sVar.recordGlobalCircle[act_id] = 1
	end
	--print("sVar.recordGlobalCircle[act_id] ="..sVar.recordGlobalCircle[act_id])
	--print("sVar.recordGlobalIndex[act_id] ="..sVar.recordGlobalIndex[act_id])
	if sVar.recordGlobalCircle[act_id] < circle then
		return nil, sVar.recordGlobalCircle[act_id], sVar.recordGlobalIndex[act_id]
	elseif sVar.recordGlobalCircle[act_id] == cirlce and sVar.recordGlobalIndex[act_id] <= index then
		return nil, sVar.recordGlobalCircle[act_id], sVar.recordGlobalIndex[act_id]
	end
	local returnTable = {}
	if sVar.recordGlobalCircle[act_id] == circle then
		for idx = index, sVar.recordGlobalIndex[act_id] - 1 do
			local data = {}
			if not sVar.recordGlobalData[act_id][idx] then
				sVar.recordGlobalData[act_id][idx] = {}
			end
			data.param = sVar.recordGlobalData[act_id][idx].param
			data.param1 = sVar.recordGlobalData[act_id][idx].param1
			data.param2 = sVar.recordGlobalData[act_id][idx].param2
			data.param3 = sVar.recordGlobalData[act_id][idx].param3
			table.insert(returnTable, data)
		end
	elseif sVar.recordGlobalCircle[act_id] - circle == 1 then
		if index < sVar.recordGlobalIndex[act_id] then
			index = sVar.recordGlobalIndex[act_id]
		end
		for idx = index, len do
			local data = {}
			if not sVar.recordGlobalData[act_id][idx] then
				sVar.recordGlobalData[act_id][idx] = {}
			end
			data.param = sVar.recordGlobalData[act_id][idx].param
			data.param1 = sVar.recordGlobalData[act_id][idx].param1
			data.param2 = sVar.recordGlobalData[act_id][idx].param2
			data.param3 = sVar.recordGlobalData[act_id][idx].param3
			table.insert(returnTable, data)
		end
		for idx = 1, sVar.recordGlobalIndex[act_id] - 1 do
			local data = {}
			if not sVar.recordGlobalData[act_id][idx] then
				sVar.recordGlobalData[act_id][idx] = {}
			end
			data.param = sVar.recordGlobalData[act_id][idx].param
			data.param1 = sVar.recordGlobalData[act_id][idx].param1
			data.param2 = sVar.recordGlobalData[act_id][idx].param2
			data.param3 = sVar.recordGlobalData[act_id][idx].param3
			table.insert(returnTable, data)
		end
	elseif sVar.recordGlobalCircle[act_id] - circle > 1 then
		for idx = sVar.recordGlobalIndex[act_id], len do
			local data = {}
			if not sVar.recordGlobalData[act_id][idx] then
				sVar.recordGlobalData[act_id][idx] = {}
			end
			data.param = sVar.recordGlobalData[act_id][idx].param
			data.param1 = sVar.recordGlobalData[act_id][idx].param1
			data.param2 = sVar.recordGlobalData[act_id][idx].param2
			data.param3 = sVar.recordGlobalData[act_id][idx].param3
			table.insert(returnTable, data)
		end
		for idx = 1, sVar.recordGlobalIndex[act_id] - 1 do
			local data = {}
			if not sVar.recordGlobalData[act_id][idx] then
				sVar.recordGlobalData[act_id][idx] = {}
			end
			data.param = sVar.recordGlobalData[act_id][idx].param
			data.param1 = sVar.recordGlobalData[act_id][idx].param1
			data.param2 = sVar.recordGlobalData[act_id][idx].param2
			data.param3 = sVar.recordGlobalData[act_id][idx].param3
			table.insert(returnTable, data)
		end
	end
	return returnTable, sVar.recordGlobalCircle[act_id], sVar.recordGlobalIndex[act_id]
end

--清除世界信息 act_id定义到GlobalDefine中的RecordTableIndexDefine里面
--data包含4个参数，至少一个参数不为nil
function clearRecordGlobalTableData(act_id)
	local sVar = InfoGlobalTable
	if sVar.recordGlobalData and sVar.recordGlobalData[act_id] then
		if sVar.recordGlobalCircle and sVar.recordGlobalCircle[act_id] then
			sVar.recordGlobalCircle[act_id] = nil
		end
		if sVar.recordGlobalIndex and sVar.recordGlobalIndex[act_id] then
			sVar.recordGlobalIndex[act_id] = nil
		end
		sVar.recordGlobalData[act_id] = nil
	end
end

function  GetItemQualityColor(quality)
    if  quality == 0 then
		return "FFFFFFFF";
    elseif quality == 1 then
		return "FF0AB41E";
	elseif quality == 2 then
		return "FF147ED7";
    elseif quality == 3 then
		return "FFBC40F6";
	elseif quality == 4 then
		return "FFFF4848";
	elseif quality == 5 then
		return "FFFF8F45";
	elseif quality == 6 then
		return "FFFFFFFF";
	end
end

--[[
初始化需要掉线恢复的副本列表
idx : 副本对应的登陆功能idx
fubenInitPanelFunc：副本初始化面板
]]
function SetNeedReloginFuben( fubenId, reloginIdx, reloginFubenFunc )
	--print("SetNeedReloginFuben, reloginIdx="..reloginIdx..", fubenId="..fubenId)
	if not reloginIdx or reloginIdx < 0 then
		print(" the idx for relogin fuben is nil or 0 ")
		return
	end

	if not reloginFubenFunc then
		print(" the reloginFubenFunc for relogin fuben is nil")
		return
	end

	if fubenId <= 0 then
		return
	end

	if not GlobalLuaConfig.reloginFubenList then
		GlobalLuaConfig.reloginFubenList = {}
	end
	--print("SetNeedReloginFuben, fubenId="..fubenId..", idx="..idx)
	GlobalLuaConfig.reloginFubenList[fubenId] = reloginIdx
	GlobalLuaConfig.reloginFuben.reloginProc[reloginIdx].getFubenFunc = reloginFubenFunc
end

--[[
获取从开始时间到截止时间的时间差（单位：秒）
]]
function GetDiffBetweenTwoTimes( beginTime, endTime )
	--计算当前时间到最后截止时间的时间差
	if not beginTime and not endTime then				--不可以两个入参都为nil
		return 0 
	end
	
	local nBeginTime 	= 0 				--开始短时间
	local nEndTime 		= 0 				--结束短时间
	local nNowTime		= 0
	if beginTime then
		local year, month, day, hour, minute, second = beginTime[1], beginTime[2], beginTime[3], beginTime[4], beginTime[5], beginTime[6]
		if not year and not month and not day then
			year, month, day = System.getDate(0, 0, 0)		--没有指定年月日，就取当前日期
		end
		nBeginTime = System.encodeNumTime(year, month, day, hour, minute, 0)
	else
		nBeginTime  = System.getCurrMiniTime()
	end

	if endTime then
		local year, month, day, hour, minute, second = endTime[1], endTime[2], endTime[3], endTime[4], endTime[5], endTime[6]
		if not year and not month and not day then
			year, month, day = System.getDate(0, 0, 0)		--没有指定年月日，就取当前日期
		end
		nEndTime = System.encodeNumTime(year, month, day, hour, minute, 0)
	else
		nEndTime  = System.getCurrMiniTime()
	end

	return nEndTime - nBeginTime
end

function ParseBigNumberToNumbers( bigNumber, smallNumber )
	if smallNumber <= 0 then
		return nil
	end

	local numList = {}
	if bigNumber <= smallNumber then
		return { bigNumber }
	else
		local addNum = 0
		local num = math.ceil( bigNumber/smallNumber )
		for i=1, num do
			if i < num then
				addNum = addNum + smallNumber
				table.insert( numList, smallNumber )
			else
				local  lastNum = bigNumber - addNum
				table.insert( numList, lastNum )
			end
		end		
	end
	return numList
end


--[[
给实体增加额外属性
sign:0-正值，1-负值
function AddAdditionalAttrToEntity( sysarg, attrType, sign, attrValue, rate )
	local theRate = rate
	if not theRate then
		theRate = 1
	end
	local theAttrValue = attrValue * theRate
	--print("AddAdditionalAttrToEntity, attrType="..attrType..", sign="..sign..", attrValue="..attrValue..", theAttrValue="..theAttrValue)
	if theAttrValue <= 65535 then
		Actor.addAdditionalAttr( sysarg, attrType, sign, theAttrValue )
	else
		local addAttrValues = ParseBigNumberToNumbers( theAttrValue, 65535 ) 		--超过65535，需要分解
		for i, value in ipairs( addAttrValues  ) do
			Actor.addAdditionalAttr( sysarg, attrType, sign, value )
			--print(" ->CreateBloodFightBoss, attrType="..attrType..", theAttrValue="..theAttrValue)
		end
	end
end
]]

--[[
给实体增临时属性
]]
function AddTemporaryAttrToEntity( sysarg, attrType, attrValue, rate )
	local theRate = rate
	if not theRate then
		theRate = 1
	end
	local theAttrValue = attrValue * theRate
	--print("->AddTemporaryAttrToEntity, attrType="..attrType..", attrValue="..attrValue..", theAttrValue="..theAttrValue)
	Actor.addTemporaryAttr( sysarg, attrType, theAttrValue )
end

function ClearActorAllBuffs( sysarg, buffs )
	for idx, buffId in ipairs( buffs ) do
		if Actor.hasBuffById( sysarg, buffId ) then
			Actor.delBuffById( sysarg, buffId )
		end
	end
end

